<template>
  <div style="border: 1px solid #ccc; margin-top: 10px">
    <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="props.toolbarMode"
      style="border-bottom: 1px solid #ccc" />
    <Editor :defaultConfig="editorConfig" :mode="props.editMode" v-model="valueHtml"
      style="height: 400px; overflow-y: hidden" @onCreated="handleCreated" @onChange="handleChange"
      @onDestroyed="handleDestroyed" @onFocus="handleFocus" @onBlur="handleBlur" @customAlert="customAlert"
      @customPaste="customPaste" />
  </div>
</template>
<script lang="ts" setup>
import { shallowRef, onBeforeUnmount, ref, nextTick, onMounted, computed } from "vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { message } from "ant-design-vue";
import _ from "lodash";
import http from "@/common/http/request";
import { useStore as useUserStore } from "@/store/user";
const userStore = useUserStore();
const token = computed(() => {
  return userStore.info.token || '';
})
const props = defineProps({
  // 编辑器内容
  modelValue: {
    type: String,
    default: "",
  },
  // 工具栏配置
  toolbarConfig: {
    type: Object,
    default: () => { },
  },
  // 工具栏模式
  toolbarMode: {
    type: String,
    default: "default",
  },
  // 编辑器配置
  editorConfig: {
    type: Object,
    default: () => { },
  },
  // 编辑器模式
  editMode: {
    type: String,
    default: "default",
  },
});
const emit = defineEmits(["update:modelValue"]);
// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();
const valueHtml = ref('');
const loaded = ref(false);
// 工具栏配置
let toolbarConfig = ref(_.assign({}, props.toolbarConfig));

toolbarConfig.value.excludeKeys = [];

// 编辑器配置
let editorConfig = ref(
  _.assign(
    {
      placeholder: "请输入内容,如果放入图片请调整百分百",
      MENU_CONF: {
        uploadImage: {},
        uploadVideo: {},
      },
    },
    props.editorConfig
  )
);

editorConfig.value.MENU_CONF["uploadImage"] = {
  // 上传图片的配置
  fieldName: "file",
  maxFileSize: 20 * 1024 * 1024, // 1M、
  server: process.env.VUE_APP_BASE_API + "common/upload",
  headers: {
    Authorization: `Bearer ${token.value}`,
  },
  customInsert: (res: any, insertFn: any) => {
    const apibaseInstance = new http();
    res = apibaseInstance.dealResponse(res);
    const code = res.code || null;
    console.log(res);
    if (code === 200) {
      insertFn(res.ossUpload.fileUrl || "", "", "");
    }
  },
};

editorConfig.value.MENU_CONF["uploadVideo"] = {
  // 上传视频的配置
  fieldName: "file",
  maxFileSize: 1024 * 1024 * 1024, // 1M、
  server: process.env.VUE_APP_BASE_API + "common/upload",
  headers: {
    Authorization: `Bearer ${token.value}`,
  },
  customInsert: (res: any, insertFn: any) => {
    const apibaseInstance = new http();
    res = apibaseInstance.dealResponse(res);
    const code = res?.code || null;
    if (code === 200) {
      let video = res.ossUpload.fileUrl || "";
      let poster = video ? video + "?x-oss-process=video/snapshot,t_0,f_jpg" : "";
      insertFn(video, poster);
    }
  },
};

// 编辑器回调函数
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
// 编辑器内容变更触发
const handleChange = (editor: any) => {
  if (!loaded.value) {
    return;
  }
  emit("update:modelValue", editor.getHtml());
};
// 编辑器销毁时触发
const handleDestroyed = (editor: any) => { };
// 编辑器聚焦时触发
const handleFocus = (editor: any) => { };
// 编辑器失去焦点时触发
const handleBlur = (editor: any) => {
  // emit("update:modelValue", editor.getHtml());
};
// 编辑器提示信息
const customAlert = (info: string, type: string) => {
  switch (type) {
    case "success":
      message.success(info);
      break;
    case "info":
      message.info(info);
      break;
    case "warning":
      message.warning(info);
      break;
    case "error":
      message.error(info);
      break;
    default:
      message.info(info);
      break;
  }
};
const customPaste = (editor: any, event: any, callback: any) => {
  callback(true);
};

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;

  editor.destroy();
});

const initValueHtml = (val: string) => {
  valueHtml.value = val;
  nextTick(() => {
    loaded.value = true;
  })
};

defineExpose({
  initValueHtml,
});
</script>
<style lang="less" scoped>
::v-deep(.w-e-text-container) {
  [data-slate-editor] {
    padding: 10px;

    p {
      margin: 0 !important;
    }
  }
}
</style>